class Solution {
    public int[][] generateMatrix(int n) {
        int[][] nex = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int[][] ans = new int[n][n];
        int x = 0, y = -1;
        int index = 1;
        int k = 0;
        while (true) {
            if (index > n * n)
                break;
            int tx = x + nex[k][0];
            int ty = y + nex[k][1];
            if (tx < 0 || tx >= n || ty < 0 || ty >= n || ans[tx][ty] != 0) {
                k = (k + 1) % 4;  // 如果碰壁了，就顺时针旋转
                continue;
            }
            ans[tx][ty] = index++;
            x = tx;
            y = ty;
        }
        return ans;
    }
}